#! /bin/bash

# Copyright (c) 2014 Albert Graef

# Copying and distribution of this file, with or without modification, are
# permitted in any medium without royalty provided the copyright notice and
# this notice are preserved.  This file is offered as-is, without any
# warranty.

# NOTE: To make this script self-contained, it includes embedded awk
# scripts. Do not remove the marker comments at the beginning and end of the
# awk scripts, otherwise we won't be able to find and extract them from the
# script source!

prog=`basename "$0"`

usage() {
  echo "USAGE: $prog [options ...] [file ...]" >&2
  echo "Options marked [pandoc] are simply passed to pandoc." >&2
  echo "General options:" >&2
  echo "-h, --help:            print this message and exit" >&2
  echo "-O, --options:         pass any options to pandoc (cumulative)" >&2
  echo "-v, --verbose:         print debugging information to stderr" >&2
  echo "Preprocessing options:" >&2
  echo "-d, --date:            insert date for |today|" >&2
  echo "-i, --index:           create/update given index file" >&2
  echo "-N, --name:            printf template for document names" >&2
  echo "-R, --raw:             include raw markup in document" >&2
  echo "-T, --title-block:     include Pandoc-style title block" >&2
  echo "-V, --version:         insert version number for @version@" >&2
  echo "Formatting options:" >&2
  echo "-c, --collapse-items:  collapse adjacent description items" >&2
  echo "-C, --callouts:        fancier formatting of note blocks" >&2
  echo "-D, --describe:        formatting of describe blocks (regex)" >&2
  echo "-H, --headers:         use section headers for definitions" >&2
  echo "-n, --no-links:        suppress all links (show link text only)" >&2
  echo "Output options:" >&2
  echo "-o, --output:          [pandoc] name of pandoc output file" >&2
  echo "-r, --reference-links: [pandoc] use reference rather than inline links" >&2
  echo "-s, --standalone:      [pandoc] produce a standalone document" >&2
  echo "-S, --smart:           [pandoc] smart quotes, dashes etc." >&2
  echo "-t, --to:              [pandoc] pandoc output format" >&2
}

infiles=/dev/stdin
outfile=
date=`date "+%B %d, %Y"`
version="0.0"
template=
index=
options=
headers=no
no_links=no
raw=no
title_block=no
callouts=no
describe=
max_items=0
verbose=no

# If we have a Makefile in the current directory, try to determine the version
# number from there.
if [ -r Makefile ]; then
  version=`sed -E -n -e 's/^version[[:space:]]*=[[:space:]]*([^[:space:]]+)[[:space:]]*$/\1/p' Makefile`
fi

# Parse options using getopt(1).
args=`getopt -o hvd:V:i:N:To:O:c::CD::HnrRsSt: -l help,verbose,date:,version:,index:,name:,title-block,output:,options:,collapse-items::,callouts,describe::,headers,no-links,reference-links,rawstandalone,smart,to: -n "$prog" -- "$@"`
if [ $? != 0 ] ; then exit 1 ; fi
eval set -- "$args"

while true; do
  case "$1" in
    -h|--help) usage; exit 1 ;;
    -v|--verbose) verbose=yes; shift ;;
    -d|--date) date="$2"; shift 2 ;;
    -V|--version) version="$2"; shift 2 ;;
    -i|--index) index="$2"; shift 2 ;;
    -N|--name) template="$2"; shift 2 ;;
    -T|--title-block) title_block=yes; shift ;;
    -o|--output) options="$options -o $2"; outfile="$2"; shift 2 ;;
    -O|--options) options="$options $2"; shift 2 ;;
    -c|--collapse-items) max_items=${2:-9999}; shift 2 ;;
    -C|--callouts) callouts=yes; shift ;;
    -D|--describe) describe=${2:-'/(\w+(\s+\w+)*):\s+(.*)/\1: `\3`/'}; shift 2 ;;
    -H|--headers) headers=yes; shift ;;
    -n|--no-links) no_links=yes; shift ;;
    -r|--reference-links) options="$options --reference-links"; shift ;;
    -R|--raw) raw=yes; shift ;;
    -s|--standalone) options="$options -s"; shift ;;
    -S|--smart) options="$options -S"; shift ;;
    -t|--to) options="$options -t $2"; shift 2 ;;
    --) shift; break ;;
  esac
done

infiles="$@"
if [ -n "$outfile" ]; then
    outfile=`echo "$outfile" | sed -e 's?.[^./]*$??'`
    outfile=`basename $outfile`
    outfile="-v filename=$outfile"
fi

describe=$(echo $describe | sed -e 's/\\/\\\\/g')

tmpdir=`mktemp -d /tmp/pure-pandoc.XXXXXX`
auxfile=${index:-"$tmpdir/targets"}
tmpout="$tmpdir/outfile.md"

rm -Rf "$tmpdir"
mkdir -p "$tmpdir"

if [ "$verbose" == "yes" ]; then
    echo "pure-pandoc      : pandoc $options"
fi

# Note that these two commands *must* be executed in sequence, to give
# rst-pre.awk the opportunity to finish writing the index file with the RST
# link targets before rst-post.awk is run.
gawk -f <(sed -e '/^# rst-pre[.]awk$/,/^# end rst-pre[.]awk$/!d' $0) $outfile -v verbose="$verbose" -v raw="$raw" -v version="$version" -v date="$date" -v template="$template" -v title_block="$title_block" -v callouts="$callouts" -v auxfile="$auxfile" "$@" > "$tmpout" && \
pandoc -f rst -t markdown --wrap=none "$tmpout" | gawk -f <(sed -e '/^# rst-post[.]awk$/,/^# end rst-post[.]awk$/!d' $0) -v verbose="$verbose" -v headers="$headers" -v max_items="$max_items" -v describe="$describe" -v no_links="$no_links" -v auxfile="$auxfile" - | pandoc -f markdown --columns 78 $options

rc=$?
rm -Rf "$tmpdir"

exit $rc
